import React, {Component} from "react"
import "./index.scss"
import { Table, Tag, Space ,Button,Form,Modal,Input,Select,message} from 'antd';
import datamobx from "*/mobx/data"
import {observer} from "mobx-react"
import {UserOutlined,LockOutlined} from "@ant-design/icons"
import {axios } from "&/axios"
const rollList = ["普通用户","管理员","超级管理员"];
const color =  ["green","blue","red"];
const mReg = /^1(3|5|6|7|8|9)\d{9}$/;
const layout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 16,
    },
};
@observer 
 class UserList extends Component{

    componentDidMount(){
        
        if(!datamobx.userlist){
            datamobx.getUserlist("/api/getalluserlist")
        }
        
    }

    state = {
        delFlag:false,
        visible:false,
        updatevisible:false,
        item:null,
        columns:[
           {
             title: '名字',
             dataIndex: 'username',
             key: 'username',        
           },
           {
            title: '联系方式',
            dataIndex: 'mobile',
            key: 'mobile',        
          },
           {
            title: '密码',
            dataIndex: 'password',
            key: 'password',        
          },
          {    
            title: '角色',
            dataIndex: 'rolltype',
            key: 'rolltype', 
            render:(roll)=>{
                return (
                    <Tag color={color[roll-1]} key={"key"}  >
                      {rollList[roll-1]}
                    </Tag>
                  );
            } 
          },
          {    
            title: '操作',
            key: 'x', 
            render:(text)=>{
                var users={}
                if(sessionStorage.users){
                    users=JSON.parse(sessionStorage.users)
                }
                return (
                    <div>
                        <Button type="primary" size="small" disabled={users.rolltype<=text.rolltype} onClick={()=>this.showUpdateModal(text)}> 修改</Button> 
                        &nbsp;&nbsp;&nbsp;
                        <Button type="danger" size="small" disabled={users.rolltype<=text.rolltype} onClick={()=>this.showDelModal(text)}> 删除</Button>
                    </div>
                  );
            } 
          }
        ]
    }
    handleOpenModal=()=>{
        this.setState({
            visible:true,
        })
    }
    
    handleAddUser=()=>{
        this.refs.addform.validateFields()
        .then(values=>{
            // 发送ajax 
            axios.post("/api/adduser",values)
            .then(res=>{
                if(res.data.type){
                    this.setState({
                        visible:false,
                    });

                    this.refs.addform.resetFields();
                    datamobx.getUserlistSync(res.data.result);

                }else{
                    this.refs.addform.resetFields();
                }
            })
        })
        .catch(err=>{
            message.error('添加信息不对,请完善再提交');
        })
    }
    handleClose=()=>{
        this.setState({
            visible:false,
        })
    }
    handleGetRolltype=value=>{
    }
    showDelModal=(item)=>{
        this.setState({
            delFlag:true,
            item
        })
    }
    showUpdateModal=(item)=>{
        this.setState({
            updatevisible:true,
            item
        })
        setTimeout(()=>{
            this.refs.updateForm&&this.refs.updateForm.setFieldsValue({
                mobile:item.mobile,
                password:item.password,
                rolltype:item.rolltype,
                username:item.username
            })
        },30)
    } 
    hideDelUser=()=>{
        this.setState({
            delFlag:false
        })
    }
    delUserOne=()=>{
        axios.post("/api/deluserone",{
            _id:this.state.item._id
        }).then(res=>{
            if(res.data.flag){
                var userlist=datamobx.userlist.filter(item=>item._id!=this.state.item._id)
                datamobx.getUserlistSync(userlist)
            }
            this.setState({delFlag:false})
        })
    }
    handleUpdateUser=()=>{
        this.refs.updateForm.validateFields()
        .then(values=>{
            axios.post("/api/changeoneuserinfo",{
                _id:this.state.item._id,
                ...values
            }).then(res=>{
                this.setState({
                    updatevisible:false
                });
                if(res.data.type){
                    var userlist=datamobx.userlist.map((item=>{
                        if(item._id==this.state.item._id){
                            item={...item,...values}
                        }
                        return item;
                    }))
                    datamobx.getUserlistSync(userlist)
                }
            })
        }).catch(err=>{
            message.error("信息不正确，请重新提交")
        })
        
    }
    render(){
        return (
            <div>
                <h2> 用户列表 </h2> 
                <Button type="primary" size="large" onClick={this.handleOpenModal}>添加用户</Button>
                <Table 
                    dataSource={datamobx.userlist}
                    columns={this.state.columns}
                    pagination={{pageSize:5}}
                    rowKey={
                        (item)=>(item._id)
                    }
                    style={{marginTop:20}}
                >
                </Table>
                <Modal
                    title="添加用户"
                    visible={this.state.visible}
                    onOk={this.handleAddUser}
                    onCancel={this.handleClose}
                    okText="确认"
                    cancelText="取消"
                >
                    <Form
                        className="form-box"
                        {...layout}
                        name="basic"
                        ref="addform"
                        layout="vertical" // 垂直排列
                    >
                        <Form.Item
                        label="手机号"
                        name="mobile"
                        rules={[
                            {
                            required: true,
                            message: '请输入你的手机号码!',
                            },
                            {
                            pattern: mReg,
                            message:"请输入正确的手机号"
                            }
                        ]}
                        >

                        <Input 
                        prefix={<UserOutlined className="site-form-item-icon" />}
                        placeholder="请输入手机号"
                        />
                        </Form.Item>
                        <Form.Item
                        label="用户名"
                        name="username"
                        rules={[
                            {
                                required: true,
                                message: '请输入你的用户名',
                            },
                            {
                                max:8,
                                min:2,
                                message:"用户名长度不对"
                            }
                        ]}
                        >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            placeholder="请输入用户名"
                        />
                        </Form.Item>
                        <Form.Item
                        label="角色"
                        name="rolltype"
                        rules={[
                            {
                            required: true,
                            message: '请选择用户角色',
                            },
                        ]}
                        >
                        <Select
                        onChange={this.handleGetRolltype}
                        placeholder="请选择角色"
                        >
                            {
                                rollList.map((item,i)=>(
                                    <Select.Option key={i+1} value={i+1} > {item}</Select.Option>
                                ))
                            }
                        </Select>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal
                    title="删除提示"
                    visible={this.state.delFlag}
                    onOk={this.delUserOne}
                    onCancel={this.hideDelUser}
                    okText="确认"
                    cancelText="取消"
                >
                    <p>你确定要删除吗...</p>
                </Modal>


                <Modal
                    title="修改用户"
                    visible={this.state.updatevisible}
                    onOk={this.handleUpdateUser}
                    onCancel={()=>this.setState({updatevisible:false})}
                    okText="确认"
                    cancelText="取消"
                >
                    <Form
                        className="form-box"
                        {...layout}
                        name="basic"
                        ref="updateForm"
                        layout="vertical" // 垂直排列
                    >
                        <Form.Item
                        label="手机号"
                        name="mobile"
                        rules={[
                            {
                            required: true,
                            message: '请输入你的手机号码!',
                            },
                            {
                            pattern: mReg,
                            message:"请输入正确的手机号"
                            }
                        ]}
                        >

                        <Input 
                        prefix={<UserOutlined className="site-form-item-icon" />}
                        placeholder="请输入手机号"
                        disabled
                        />
                        </Form.Item>
                        <Form.Item
                        label="用户名"
                        name="username"
                        rules={[
                            {
                                required: true,
                                message: '请输入你的用户名',
                            },
                            {
                                max:8,
                                min:2,
                                message:"用户名长度不对"
                            }
                        ]}
                        >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            placeholder="请输入用户名"
                        />
                        </Form.Item>
                        <Form.Item
                        label="密码"
                        name="password"
                        rules={[
                            {
                                required: true,
                                message: '请输入你的密码',
                            },
                            {
                                max:12,
                                min:2,
                                message:"密码长度不对"
                            }
                        ]}
                        >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            placeholder="请输入密码"
                        />
                        </Form.Item>
                        <Form.Item
                        label="角色"
                        name="rolltype"
                        rules={[
                            {
                            required: true,
                            message: '请选择用户角色',
                            },
                        ]}
                        >
                        <Select
                        onChange={this.handleGetRolltype}
                        placeholder="请选择角色"
                        >
                            {
                                rollList.map((item,i)=>(
                                    i!==2&&<Select.Option key={i+1} value={i+1} > {item}</Select.Option>
                                ))
                            }
                        </Select>
                        </Form.Item>
                    </Form>
                </Modal>
            
            </div>
        )
    }
}
export default UserList